import { defineStore } from 'pinia'
import { fetchUserInfo, login as userLogin, logout as userLogout, type LoginData } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'
import type { UserState } from './types'
import { useStorage } from '@vueuse/core'
import { StoreKey } from '@/config/constants'
// import { resetRouter } from '@/router'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    nickName: undefined,
    avatar: undefined,
    job: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    introduction: undefined,
    personalWebsite: undefined,
    jobName: undefined,
    organizationName: undefined,
    locationName: undefined,
    phone: undefined,
    registrationDate: undefined,
    accountId: undefined,
    certification: undefined,
    roles: '',
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
  },

  actions: {
    // Reset user's information
    reset() {
      this.$reset()
    },

    // 获取用户信息
    async getUserInfo(id: string) {
      return new Promise((resolve, reject) => {
        fetchUserInfo(id)
          .then(({ data }: any) => {
            if (!data) {
              return reject('Verification failed, please Login again.')
            }

            const { nickName, avatar, roles } = data

            if (!roles || roles.length <= 0) {
              reject('getUserInfo: roles must be a non-null array!')
            }
            this.nickName = nickName
            this.avatar = avatar
            this.roles = roles

            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm)
        useStorage(`${StoreKey}-user`, res)
        setToken(res.token)
      } catch (err) {
        removeToken()
        throw err
      }
    },

    // Logout
    async logout() {
      await userLogout()

      this.reset()
      // resetRouter()
      removeToken()
    },
  },
})

export default useUserStore
